package com.itheima.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private Map<String,User> map = new HashMap<String,User>();

    private void init(){
        User user = new User();
        user.setUsername("zhangsan");
        user.setPassword(bCryptPasswordEncoder.encode("123"));
        map.put(user.getUsername(),user);

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword(bCryptPasswordEncoder.encode("123"));
        map.put(user2.getUsername(),user2);

    }

    /**
     *
     * 当用户登陆时会调用该方法，并且将用户的登陆名称通过该方法的参数传递进来
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //初始化数据库
        init();
        //通过登陆的用户名从数据库中查询用户信息
        User user = map.get(username);

        //通过一个List给用户进行授权
        List<GrantedAuthority> list = new ArrayList<>();
        /**
         * 授权的规则：
         *      1、给用户授予角色
         *          ROLE_角色名称，全字母大写
         *      2、给用户配置crud权限
         *          没有ROLE_前缀的名称就是用来配置权限的，大小写都可。
         */
        if (username.equals("zhangsan")){
            list.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
            list.add(new SimpleGrantedAuthority("add"));
        }
        if (username.equals("lisi")){
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            list.add(new SimpleGrantedAuthority("update"));
        }

        //密码前+“{noop}”表示这个是明文密码，没有被加密过
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode("123");
        String encode2 = passwordEncoder.encode("123");
        System.out.println(encode);
        System.out.println(encode2);

        boolean flag = passwordEncoder.matches("123", encode);
        boolean flag2 = passwordEncoder.matches("123", encode2);
        System.out.println(flag);
        System.out.println(flag2);
    }
}
